import { Checkbox,Tag,Row, Col} from 'antd';
import React, { PureComponent } from 'react';

const CheckboxGroup = Checkbox.Group;

class CheckTagbox extends PureComponent {
    constructor(props) {
        super(props);
       
        this.state = {
          checkedList: [],
          checkAll:this.props.parenChecked,
        };
      }

      onChange = (checkedList) => {
        const checkAll = checkedList.length > 0
        const {form,titleIndex} = this.props;  
        const checkObj = {};
        checkObj[titleIndex] = checkAll;
        form.setFieldsValue(checkObj);

        this.setState({
          checkedList,
          checkAll,
        });
      }
    
      onCheckAllChange = (e) => {
        const {options,form,titleIndex} = this.props;   
        const {
            getFieldDecorator,
        } = form;
        const checkedList = options.map( record => {
          return record.value;
        })
        const newCheckedList = e.target.checked ? checkedList : [];
        const checkObj = {};
        checkObj[titleIndex] = newCheckedList;
        form.setFieldsValue(checkObj);
        this.setState({
          checkedList: newCheckedList,
          checkAll: e.target.checked,
        });
      }  

      render(){
        const {options,form,dataIndex,title,titleIndex,parentValue} = this.props;  
        const {
            getFieldDecorator,
        } = form;
        const defaultValue = [];
        for(const option of options){
          if(option.defaultChecked){
            defaultValue.push(option.value);
          }
        }
        return (
          <Row style={{width:"100%"}}>
           
            <Col span={3}>
              {getFieldDecorator(titleIndex,{initialValue:this.state.checkAll})(
                <Checkbox
                  onChange={this.onCheckAllChange}
                  checked={this.state.checkAll}
                  value={parentValue}
                >
                  <span style={{fontWeight:'bold',color:'#000'}}>{title}</span>
                </Checkbox>
             )}
            </Col>  
            <Col span={21}>
              {getFieldDecorator(dataIndex,{initialValue:defaultValue})(
                <CheckboxGroup onChange={this.onChange}>
                  <Row>
                    {options.map((record,index) => {
                return (
                  <Col span={3} style={{width:120}} key={index}>
                    <Checkbox value={record.value}><Tag style={{display:'inline'}}>{record.label}</Tag></Checkbox>
                  </Col>
                )
              })}
                  </Row>
                </CheckboxGroup>
            )}
            </Col>
          </Row>);
      }
}

export default CheckTagbox;